// pages/chat/chat.js

let app = getApp()

import {
  requestUtil,
  getImgUrl
} from "../../utils/requestApi"
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // emoJi:app.globalData.emojiArr,
    messageText: "",
    // 键盘与声音的切换
    voice: true,
    fc: false,
    botHeight: 293,
    botBoolean: false,
    isPlusFile: false,
    userInfo: {},
    friendId: 0,
    chatMess: [],
    imgUrl: "",
    messageText_code:""
  },
  // 聚焦时滚到底部
  scrollBot() {
    this.scrollBotton(".huan")
  },
  // 把内容添加到messageText
  addmessageText(e) {
    // console.log(e)/

    let value = e.detail.value.substr(this.data.messageText.length)

    // console.log(value)
    if(value){
      this.setData({
        messageText:this.data.messageText+value,
        messageText_code:this.data.messageText_code+value
      })
    }else{
      // let a =this.data.messageText.slice(0,this.data.messageText.length-1)
      // let b= this.data.messageText_code.slice(0,this.data.messageText_code.length-1)
      this.setData({
        messageText:"",
        messageText_code:""
      })
    }
    
  },

  // 文字加表情包
  emoFnct(e){
    // console.log(e.detail,"detail")
      let obj = {}
       app.globalData.emojiArr.map(item => {
          if(item.code==e.detail){
            // console.log(item,"fesefs")
            obj = JSON.parse(JSON.stringify(item))
          }
      })
      // console.log(obj,"obj")
      this.setData({
        messageText:this.data.messageText+obj.emoji,
        messageText_code:this.data.messageText_code+obj.code
      })
  },

  // 长按录音
  handleRecordStart() {
    console.log("长按录音")
    //   const recorderManager = wx.getRecorderManager()
    // //设置录音参数
    // const options = {
    //   duration: 10000,
    //   sampleRate: 16000,
    //   numberOfChannels: 1,
    //   encodeBitRate: 48000,
    //   format: 'mp3'
    // }
    // //开始录音
    //   recorderManager.start(options)
  },

  

  // 滚动带底部
  scrollBotton(a, dis = 200) {
    // console.log(a)
    wx.pageScrollTo({
      duration: dis,
      selector: a,
    })
  },

  // 点击语音
  voice(e) {
    // this.scrollBotton(".bot")
    if (!this.data.voice) {
      this.setData({
        fc: true,
      })
    } else {
      this.setData({
        botBoolean: false,
        isPlusFile: false
      })
    }
    this.setData({
      voice: !this.data.voice
    })

    console.log("发语音")
  },

  // 添加文件
  plusFile() {
    console.log("添加文件")
    this.setData({
      isPlusFile: true,
      botBoolean: false,
      fc: false,
      voice: true
    })
    this.scrollBotton(".huan")
  },

  // 点击表情包
  emobtn(e) {
    this.setData({
      botBoolean: true,
      isPlusFile: false,
      fc: false,
      voice: true
    })
    this.scrollBotton(".huan")
    // wx.onKeyboardHeightChange(res => {
    //   console.log(res,'res')
    // })
  },

  // 关闭closebotBoolean
  closebotBoolean() {
    this.setData({
      botBoolean: false,
      isPlusFile: false
    })
  },

  //   输入宽底部不能移动
  noMove() {
    return
    console.log("ffesfes")
  },

  //   发送消息
  emitMess() {
    // console.log(this.data.messageText_code,"parent   yao")
    // let a = this.decode(this.data.messageText_code)
    // return

    let relation = this.data.userInfo.id + this.data.friendId
    let info = {
      message: this.data.messageText_code,
      myId: this.data.userInfo.id,
      relation: relation,
      mesType: 3
    }
    // console.log(info)
    // return
    let res = requestUtil({
      url: "/my/emitFriendMess",
      method: "get",
      data: info,
    })
    res.then(r => {
      if (r.data.code == 200) {
        // console.log(r, "fesfes")
        this.getFriendChatMess(relation)
        
        this.setData({
          messageText: "",
           botBoolean: false,
            isPlusFile: false,
        })
        let a = {
          friendId: this.data.friendId
        }
        let socket = app.globalData.socket
        socket.emit("friendMess",this.data.friendId)

      } else {
        console.log("失败")
      }
    })
  },
  // 转码
  decode(str){
    let tempArr = str.split(/[\#,_]/)
    let newArr = tempArr.filter(value => value)
    for(let i=0;i<newArr.length;i++){
      for(let j=0;j<(app.globalData.emojiArr).length;j++){
        if(newArr[i].indexOf('emo')!=-1 &&(app.globalData.emojiArr[j]).code.indexOf(newArr[i])!=-1){
          newArr[i] = (app.globalData.emojiArr[j]).emoji
        }
      }
    }
    let strLen = ""
    // console.log(newArr,"newArr")
    for(let i =0;i<newArr.length;i++){
      strLen +=newArr[i]
    }
    // console.log(strLen)
    return strLen
  },





  // 选择图片
  // /alongImage
  afterRead(event) {

    wx.chooseMedia({
      count: 1,
      sizeType: ['original', 'compressed'],
      mediaType: ['image', 'video'],
      sourceType: ['album', 'camera'],
      camera: 'back',
      success: (res) => {
        // console.log(res)
        // console.log(res.tempFiles[0].tempFilePath)
        let imgUrl = res.tempFiles[0].tempFilePath
        // let imgUrl = res.tempFilePaths[0]
        this.uploadImage(imgUrl)
        // https://61211w73f7.zicp.fun/alongImage/alongUpload

      }
    })
  },

  // 上传图片
  uploadImage(e) {
    console.log(e, "e")
    // let a = "https://61211w73f7.zicp.fun/image/1671093444559.jpg"
    wx.uploadFile({
      url: 'https://61211w73f7.zicp.fun/alongImage/alongUpload',
      filePath: e,
      name: 'avator',
      header:{
        // "Content-Type":"application/json"
         //这里修改json为text   json的话请求会返回400（bad request）
         "Content-Type": "json"
       },
      success(res) {
        console.log(res, "res")
      },
      fail: (err) => {
        console.log(err,"err")
      }
    })
  },

  //   获取用户的聊天信息
  getFriendChatMess(e) {
    // console.log(e,"fesfes")
    let res = requestUtil({
      url: "/my/getFriendMess",
      method: "get",
      data: {
        relation: e
      }
    })

    res.then(r => {
      // console.log(r.data.code)
      if (r.data.code == 200) {
        r.data.data.forEach(item=>{
         
          if(item.message){
            // console.log(item.message)
            item.message = this.decode(item.message)
          }
        })
        this.setData({
          chatMess: r.data.data
        })
        this.scrollBotton(".huan", 100)
      } else {
        this.setData({
          chatMess: []
        })
      }
    })
  },

  // 监听好友的发信息

  onFriendMess() {
    let relation = this.data.userInfo.id + this.data.friendId
    // console.log(relation,"relation")
    let myId = this.data.userInfo.id

    let socket = app.globalData.socket
    socket.on(myId, (data) => {
      this.getFriendChatMess(relation)
    })



  },

  // 获取用户的信息
  getUserinfo() {
    wx.getStorage({
      key: "userInfo",
      success: (res) => {
        let userinfo = JSON.parse(res.data)
        this.setData({
          userInfo: userinfo
        })
        this.onFriendMess()
      }
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    if (options) {
      // console.log(options,"options")
      this.setData({
        friendId: parseInt(options.friendId),
        relation: options.relation
      })
      this.getFriendChatMess(options.relation)
    }
    this.getUserinfo(),
      this.setData({
        imgUrl: getImgUrl()
      })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    setTimeout(() => {
      wx.pageScrollTo({
        duration: 0,
        selector: ".huan",
      })
    }, 50);
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})